package com.cci.kangdao.utilTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

/**
 * 通过经度、纬度获取两点之间路程距离
 * @author baiyunjiao
 *
 */
public class GetDistance {
    private final static Logger LOG = Logger.getLogger(GetDistance.class);
	 public static void main(String[] args){
	        String start = "河北省石家庄市桥西区";
	        String end = "大庆嘉吉祥汽车销售有限公司";
	 
	        String startLonLat = getLonLat(start);
	        String endLonLat = getLonLat(end);
	 
	        System.out.println(startLonLat);
	        System.out.println(endLonLat);
//	        Long dis = getDistance(startLonLat,endLonLat);
	        Double dis = getDistance(startLonLat,endLonLat);
	        System.out.println(dis);
	    }
	 
	    public static String getLonLat(String address){
	        //返回输入地址address的经纬度信息, 格式是 经度,纬度
	        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=f238f40eb92f5e1630ff216238ea372b&address="+address;
	        String queryResult = getResponse(queryUrl);  //高德接品返回的是JSON格式的字符串
	 
	        JSONObject jo = new JSONObject().fromObject(queryResult);
	        JSONArray ja = jo.getJSONArray("geocodes");
	        return new JSONObject().fromObject(ja.getString(0)).get("location").toString();
	    }
	    /**
	     * 这个方法默认是两点间驾车距离  不适用于东康二网站内单超距离审批的里程计算，下面新写了一个方法，计算两点间直线距离
	     * @param startLonLat 服务站经纬度（“lon,lat”）
	     * @param endLonLat 故障点经纬度（“lon,lat”）
	     * @return
	     */
	    public static Double getDistance(String startLonLat, String endLonLat){
	        //返回起始地startAddr与目的地endAddr之间的距离，单位：米
//	        Long result = new Long(0);
            Double result = new Double(0);
            try {
                String queryUrl = "http://restapi.amap.com/v3/distance?key=f238f40eb92f5e1630ff216238ea372b&origins=" + startLonLat + "&destination=" + endLonLat;
                String queryResult = getResponse(queryUrl);
                String requestLog = String.format("访问高德获取地址信息，请求：%s,响应：%s", queryUrl, queryResult);
                LOG.info(requestLog);
                JSONObject jo = new JSONObject().fromObject(queryResult);
                JSONArray ja = new JSONArray();
                if (jo.containsKey("results")) {
                    ja = jo.getJSONArray("results");
                } else {
                    return 0.0;
                }
//	        result = Long.parseLong(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
//	        result = Double.parseDouble(new JSONObject().fromObject(ja.getString(0)).get("distance").toString())/1000;
                result = new BigDecimal(Double.parseDouble(new JSONObject().fromObject(ja.getString(0)).get("distance").toString()) / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

//	        return queryResult;
            } catch (Exception e) {
                LOG.error("高德获取地址信息发生异常，异常：" + e);
			}
            return result;
	    }


	/**
	 * 这个方法是计算两点间直线距离   东康二网站内单超距离审批距离计算使用这个
	 * @param startLonLat 服务站经纬度（“lon,lat”）
	 * @param endLonLat 故障点经纬度（“lon,lat”）
	 * @return
	 */
	public static Double getLineDistance(String startLonLat, String endLonLat,int type){
		//返回起始地startAddr与目的地endAddr之间的距离，单位：米
//	        Long result = new Long(0);
		Double result = new Double(0);
		try {
			String queryUrl = "http://restapi.amap.com/v3/distance?key=f238f40eb92f5e1630ff216238ea372b&origins=" + startLonLat + "&destination=" + endLonLat+"&type="+type;
			String queryResult = getResponse(queryUrl);
			String requestLog = String.format("访问高德获取地址信息，请求：%s,响应：%s", queryUrl, queryResult);
			LOG.info(requestLog);
			JSONObject jo = new JSONObject().fromObject(queryResult);
			JSONArray ja = new JSONArray();
			if (jo.containsKey("results")) {
				ja = jo.getJSONArray("results");
			} else {
				return 0.0;
			}
//	        result = Long.parseLong(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
//	        result = Double.parseDouble(new JSONObject().fromObject(ja.getString(0)).get("distance").toString())/1000;
			result = new BigDecimal(Double.parseDouble(new JSONObject().fromObject(ja.getString(0)).get("distance").toString()) / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();

//	        return queryResult;
		} catch (Exception e) {
			LOG.error("高德获取地址信息发生异常，异常：" + e);
		}
		return result;
	}

	 
	    public static String getResponse(String serverUrl){
	        //用JAVA发起http请求，并返回json格式的结果
	        StringBuffer result = new StringBuffer();
	        try {
	            URL url = new URL(serverUrl);
	            URLConnection conn = url.openConnection();
	            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	 
	            String line;
	            while((line = in.readLine()) != null){
	                result.append(line);
	            }
	            in.close();
	 
	        } catch (MalformedURLException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return result.toString();
	    }
}
